package org.app.controller;

import org.app.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {
    
    @Value("${file.upload.path:./upload}")
    private String uploadPath;
    
    /**
     * 上传图片文件
     */
    @PostMapping("/upload")
    public Result<String> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "type", defaultValue = "image") String type,
            HttpServletRequest request) {
        System.out.println("接收到文件上传请求: " + file.getOriginalFilename() + ", 类型: " + type);
        
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return Result.error("上传的文件不能为空");
        }
        
        try {
            // 获取项目绝对路径
            File projectDir = new File("").getAbsoluteFile();
            System.out.println("项目路径: " + projectDir.getAbsolutePath());
            
            // 创建绝对路径
            String absoluteUploadPath = projectDir.getAbsolutePath() + File.separator + uploadPath.replace("./", "");
            System.out.println("上传绝对路径: " + absoluteUploadPath);
            
            // 确保上传目录存在
            File uploadDir = new File(absoluteUploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建上传根目录 " + uploadDir.getAbsolutePath() + (created ? " 成功" : " 失败"));
            }
            
            // 构建文件保存路径
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 使用UUID作为文件名避免重复
            String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
            
            // 构建完整文件路径
            String fullFilePath = absoluteUploadPath + File.separator + fileName;
            File destFile = new File(fullFilePath);
            System.out.println("保存文件到: " + destFile.getAbsolutePath());
            
            // 直接使用文件流写入，不使用transferTo
            try (
                InputStream in = file.getInputStream();
                FileOutputStream out = new FileOutputStream(destFile)
            ) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            }
            
            if (!destFile.exists()) {
                System.out.println("文件保存失败: 文件不存在");
                return Result.error("文件保存失败: 文件未成功写入");
            }
            
            System.out.println("文件保存成功: " + destFile.getAbsolutePath());
            
            // 返回相对路径 (不包含域名和端口)
            String relativePath = "/upload/" + fileName;
            System.out.println("文件相对路径: " + relativePath);
            
            return Result.success(relativePath);
        } catch (Exception e) {
            System.out.println("文件上传异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过静态资源映射访问文件，不再需要这个接口
     * 配置在 WebMvcConfig 中添加静态资源映射即可
     */
    @GetMapping("/download/**")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        String filePath = requestURI.substring(requestURI.indexOf("/download/") + "/download/".length());
        
        System.out.println("请求下载文件: " + filePath);
        
        // 获取项目绝对路径
        File projectDir = new File("").getAbsoluteFile();
        String absoluteUploadPath = projectDir.getAbsolutePath() + File.separator + uploadPath.replace("./", "");
        
        File file = new File(absoluteUploadPath + File.separator + filePath);
        System.out.println("查找文件: " + file.getAbsolutePath() + " 存在: " + file.exists());
        
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在: " + file.getAbsolutePath());
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        try {
            // 根据文件扩展名设置Content-Type
            String mimeType = Files.probeContentType(Paths.get(file.getPath()));
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }
            response.setContentType(mimeType);
            System.out.println("文件Content-Type: " + mimeType);
            
            // 直接返回文件内容
            try (FileInputStream inputStream = new FileInputStream(file);
                 OutputStream outputStream = response.getOutputStream()) {
                
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.flush();
                System.out.println("文件发送完成");
            }
        } catch (IOException e) {
            System.out.println("文件下载异常: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
} 